package com.wechat.page.store;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.swak.annotation.Context;
import com.swak.annotation.FluxDepend;
import com.swak.annotation.FluxService;
import com.swak.utils.Maps;
import com.wechat.dto.ContactDTO;
import com.wechat.page.api.SubjectApi;

/**
 * ContactStore. 联系人缓存
 * 
 * @author DELL
 */
@Service
public class ContactStore implements InitializingBean {

	private static ContactStore INSTANCE = null;

	@FluxDepend
	private ContactStoreService contactStoreService;

	@Override
	public void afterPropertiesSet() throws Exception {
		INSTANCE = this;
	}

	public static CompletableFuture<ContactDTO> GetContact(String contactID) {
		return INSTANCE.contactStoreService.getContact(contactID);
	}

	public static CompletableFuture<Void> DelContact(String contactID) {
		return INSTANCE.contactStoreService.delContact(contactID);
	}

	@FluxService(context = Context.Order)
	public static class ContactStoreService {

		@Autowired
		private SubjectApi subjectApi;

		private Map<String, ContactDTO> contacts = Maps.newHashMap();

		/**
		 * 获得缓存
		 * 
		 * @param contactID
		 * @return
		 */
		public CompletableFuture<ContactDTO> getContact(String contactID) {
			if (contacts.containsKey(contactID)) {
				return CompletableFuture.completedFuture(contacts.get(contactID));
			}

			return subjectApi.contact(contactID).thenApply(contact -> {
				contacts.put(contact.getId(), contact);
				return contact;
			});
		}

		/**
		 * 删除缓存
		 * 
		 * @param contactID
		 * @return
		 */
		public CompletableFuture<Void> delContact(String contactID) {
			contacts.remove(contactID);
			return CompletableFuture.completedFuture(null);
		}
	}
}